<?php
/*
TrackBack script by martin $ 2007/11/03 11:33:24
*/

include_once('owner/ini.inc.php');
include_once('utils.php');
include_once('utils_admin.php');
include_once('session.class.php');
define('ADMIN', Auth() ? TRUE : FALSE);
include_once('cache.php');

if(test_ip($ip=$_SERVER["REMOTE_ADDR"]) > 0) _header('index.php');

$blacklist_ini = OD.'blacklist.ini.php';

if($mb==TRUE){
 mb_language("Japanese");
 mb_internal_encoding(ENCODE);
 mb_regex_encoding(ENCODE);
} else {
 if(file_exists(PATH.'jcode_wrapper.php')){
  include_once(PATH.'jcode_wrapper.php');
 } else die('Multibyte Not Supported.');
}

if(isset($_REQUEST)) $_REQ = str_replace('&amp;#', '&#', sanitize_data($_REQUEST));

$mode = isset($_REQ['mode']) ? $_REQ['mode'] : '';
$url = isset($_REQ['url']) ? $_REQ['url'] : '';
$title = isset($_REQ['title']) ? str_replace(array('&lt;','&gt;'), array('[',']'), $_REQ['title']) : '';
$title = empty($title) ? '' : preg_replace('{\[.+?\].+?\[/\w+?\]}', '', $title);
$excerpt = isset($_REQ['excerpt']) ? str_replace(array('&lt;','&gt;'), array('[',']'), $_REQ['excerpt']) : '';
$excerpt = empty($excerpt) ? '' : my_substr(preg_replace('{\[.+?\].+?\[/\w+?\]}', '', $excerpt), 0, 255);
$blog_name = isset($_REQ['blog_name']) ? strip_tags($_REQ['blog_name']) : '';
$ping_url = isset($_REQ['ping_url']) ? strip_tags($_REQ['ping_url']) : '';
$target_id = isset($_REQ['UID']) ? $_REQ['UID'] : '';

if(!ADMIN && empty($url)) return;
if(trim(MAILTO)!=''){
 include_once('modules/mail.inc.php');
 $MAIL_DACCORD = TRUE;
} else $MAIL_DACCORD = FALSE;

$target = "$title  $excerpt  $blog_name";

if($mode != 'delete' && $mode != 'cast_ping'){
 $target = my_convert_encoding($target, ENCODE, mb_detect_encoding($target, 'UTF-8,EUC-JP,SJIS,ASCII,JIS'));
 rewrite("tb.txt", $target);
 if(ACCEPT_ALNUMPING==FALSE){
  if(!mb_ereg('[ぁ-ん]+|[ァ-ヴー]+|[ａ-ｚＡ-Ｚ０-９]+', $target, $mt)){ # ひらがななしなら却下
   if($MAIL_DACCORD && TB_SPAM_REPORT){
    if(is_file(OD.'ngwords.ini.php')){
     include_once(OD.'ngwords.ini.php'); # get::NG_WORDS
     $NG = array();
     foreach($NG_WORDS as $ng){
      if(stristr($target, $ng)!==FALSE) $NG[] = $ng;
     }
     if(!empty($NG)) return;
    }
    rewrite("a.txt", "NON-Hira", TRUE);
    //send_jp_mail('ppBlog Agent::Non-Hiragana x-x-x', date('Y-m-d H:i:s')."\t".$ip."\t".$target."\t".$url."\t".$ping_url);
   }
   return;
  }
  if(preg_match('{^[\x20-\x7E]+$}', $target)){ # 概要などに日本語が含まれない or 空白の場合はTB却下
   if(!is_file($blacklist_ini)){
    $BLACK_LIST = array();
    rewrite_ini($blacklist_ini, '', '$BLACK_LIST'); # iniファイルの作成
   } else include_once($blacklist_ini); # get::BLACK_LIST
   $BLACK_LIST[] = date('Y-m-d H:i:s').urlencode('--'.$ip.'--'.$target.'--'.$url.'--'.$ping_url);
   rewrite_ini($blacklist_ini, $BLACK_LIST);
   if($MAIL_DACCORD && TB_SPAM_REPORT){
    send_jp_mail('x-x-x ブラックリスト入り by alnumonly x-x-x', date('Y-m-d H:i:s')."\t".$ip."\t".$target."\t".$url."\t".$ping_url);
   }
   return;
  }
 }
 if(ACCEPT_NGWORD==FALSE){ # NGワード拒否
  if(is_file(OD.'ngwords.ini.php')){
   include_once(OD.'ngwords.ini.php'); # get::NG_WORDS
   $NG = array();
   foreach($NG_WORDS as $ng){
    if(stristr($target, $ng)!==FALSE) $NG[] = $ng;
   }
   if(!empty($NG)){ # NGワードにヒット
    if(!is_file($blacklist_ini)){
     $BLACK_LIST = array();
     rewrite_ini($blacklist_ini, '', '$BLACK_LIST'); # iniファイルの作成
    } else {
     include_once($blacklist_ini); # get::BLACK_LIST
    }
    $BLACK_LIST[] = date('Y-m-d H:i:s').urlencode('--'.$ip.'--'.(implode(',', $NG)));
    rewrite_ini($blacklist_ini, $BLACK_LIST);
    if($MAIL_DACCORD && TB_SPAM_REPORT){
     send_jp_mail('x-x-x ブラックリスト入り by NGワード x-x-x', date('Y-m-d H:i:s')."\t".$ip."\t".$target);
    }
    return;
   }
  }
 }
 if(TB_CHECK_REFERRED==TRUE){
  if($mode==''){
   $from = get_file_content($url);
   $from = ($from=='') ? get_http($url) : $from;
   $to = preg_replace('{https?://([^/]+?)/?$}', '\\1', ROOT_PATH);
   if($from==FALSE || strpos($from, $to)===FALSE){ // こちらのブログへのリンクがなければ却下
    if($MAIL_DACCORD && TB_SPAM_REPORT==TRUE){
     send_jp_mail('ppBlog Agent::No link x-x-x', date('Y-m-d H:i:s')."[$ip][$target][$url]".$ping_url);
    }
    return;
   }
  }
 }
}

$info = array(
 'entry'     => time(),
 'url'       => rawurlencode($url),
 'title'     => rawurlencode(my_convert_encoding($title, ENCODE, 'auto')),
 'excerpt'   => rawurlencode(my_convert_encoding($excerpt, ENCODE, 'auto')),
 'blog_name' => rawurlencode(my_convert_encoding($blog_name, ENCODE, 'auto')),
 'ping_url'  => rawurlencode($ping_url)
);

$target = my_file(log_($target_id));

list($tid,$cat,$title,,,,$allowPing) = explode('|', $target[get_article_index($target_id, $target)]);

if($allowPing==FALSE) return; // 個別指定

if(preg_match("/\d{9,}/", $target_id)){
 define('TB_FILE', TB_DIR.$target_id.EXT);
 if(!file_exists(TB_FILE)) mk_fl(TB_FILE);
}

switch ($mode){
 case 'delete' :
  if(ADMIN && defined('TB_FILE')){
   $data = unserialize(get_file_content(TB_FILE));
   if(is_array($data)){
    for($i = 0; $i < count($data); $i++){
     if(preg_match('{'.g_('TBID').'}', $data[$i]['entry'])) break;
    }
   }
   array_splice($data, $i, 1);
   rewrite(TB_FILE, serialize($data));
   tb_log_scavenger();
   make_trackback_DB();
   update_cache(array('recent_trackbacks'));
   $ref = $_SERVER['HTTP_REFERER'];
   _header(strstr($ref, 'index.') ? $ref : "admin.php?mode=article&sub=trackback&UID={$target_id}");
  }
 break;

 case 'cast_ping' :
  if(ADMIN){
   if($_REQUEST['ping_url']!='') cast_ping_data();
  } else _header('index.php');
 break;
 
 default :
  if(empty($info['url']) || empty($info['title'])) tb_response("Information Not Enough!", 1);
  if(defined('TB_FILE')){
   $data = unserialize(get_file_content(TB_FILE));
   if(!is_array($data)) $data = array();
   array_unshift($data, $info);
   rewrite(TB_FILE, serialize($data));
   make_trackback_DB();
   update_cache(array('recent_trackbacks'));
   $trackback_body = NL.NL.'見てみましょう: '.ROOT_PATH.'index.php?mode=trackback&UID='.$target_id.NL
                   . '以下は新しく付いたトラックバックです。'.NL.NL
                   . 'ターゲットエントリー：'.$title.' posted @ '.date('Y-m-d H:i:s', $tid).NL
                   . '　　　　　カテゴリー：'.$cat.NL
                   . '　トラックバック日時：'.date('Y-m-d H:i:s', $info['entry']).NL
                   . '　　　　　　サイト名：'.rawurldecode($info['blog_name']).NL.NL
                   . '              概　要：'.NL.str_replace('<br />', NL, my_wordwrap(rawurldecode($info['excerpt'])));
   if(trim(MAILTO)!='') send_jp_mail("新しいトラックバックがあります", $trackback_body);
   tb_response("Thanks for trackback ping! -- ppBlog Agent");
  }
 break;
}

function my_wordwrap($string, $width=76){
 if(function_exists('mb_strcut')==true){
  $lines = explode(NL, $string);
  $trimmed = '';
  foreach($lines as $line){
   do{
    $trimmed .= mb_strcut($line, 0, $width).NL;
    $line = mb_strcut($line, $width);
   } while (strlen($line) >= $width);
   $trimmed .= $line;
  }
  return $trimmed;
 } else return $string;
}
function tb_log_scavenger(){ // 空のTBファイルは削除
 $TBS = my_glob(EXT, TB_DIR);
 if(is_array($TBS)){
  foreach($TBS as $tb){
   $tb_content = get_file_content($tb);
   if(!empty($tb_content)){
    $a = unserialize($tb_content);
    if(empty($a)) unlink($tb);
   }
  }
 }
}
?>
